import {getRequest} from "./api";
import router from "../router";

export const initMenu =(router,store)=>{
    console.log("initMenu")
    if(store.state.routes.length > 0){
        console.log("有initMenu")
        //说明vuex的routes中有数据 直接返回
        return;
    }
    console.log("没有initMenu")
    getRequest("/api/system/menu",).then(data=>{
        if (data){
            console.log("加载成功")
            //访问成功  将component的字符串转化为对象
            let fmtRoutes = formatRoutes(data);
            console.log(fmtRoutes)
            router.addRoutes(fmtRoutes);
            store.commit('inintRoutes',fmtRoutes);
            store.dispatch('connect');
        }

    })
}

export const formatRoutes=(data) =>{
    let fmRoutes = [];
    data.forEach(router =>{
        let {
            path,
            component,
            name,
            meta,
            iconCls,
            children
        } =router;
        if(children && children instanceof Array){
            children = formatRoutes(children);
        }
        let fmRouter = {
            path : path,
            name : name,
            meta : meta,
            iconCls : iconCls,
            children : children,
            component(re){
                if (component.startsWith("Home")) {
                    require(['../views/' + component + '.vue'], re);
                } else if (component.startsWith("Emp")) {
                    require(['../views/emp/' + component + '.vue'], re);
                } else if (component.startsWith("Per")) {
                    require(['../views/per/' + component + '.vue'], re);
                } else if (component.startsWith("Sal")) {
                    require(['../views/sal/' + component + '.vue'], re);
                } else if (component.startsWith("Sta")) {
                    require(['../views/sta/' + component + '.vue'], re);
                } else if (component.startsWith("Sys")) {
                    console.log("Sys")
                    console.log(component)
                    require(['../views/sys/' + component + '.vue'], re);
                } else if (component.startsWith("Order")) {
                    console.log("Order")
                    console.log(component)
                    require(['../views/order/' + component + '.vue'], re);
                }
            }
        }
        fmRoutes.push(fmRouter);
    })
    return fmRoutes;
}